<!--出库修改页面-->
<!--只允许修改基本出库单，不修改已经出库的明细数据-->
<template>
  <div class="purchase-root">
    <!--222222&#45;&#45;&#45;&#45;{{type}}***33333333-->
    <el-card shadow="never" body-style="padding: 20px 20px 0px 20px;">
      <el-form
        ref="form"
        :rules="$rules.warehouseExRules"
        inline
        :model="form"
        class="form-options"
        label-width="100px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="出库单号" prop="outNo" for="outNo">
              <el-input v-model="form.outNo" disabled id="outNo" />
            </el-form-item>
            <el-form-item label="客户" prop="customerName" for="customerName">
              <el-select
                v-model="form.customerName"
                clearable
                filterable
                placeholder="请选择客户"
                :disabled="type == 0"
                @change="handleSelectCustomer"
                id="customerName"
              >
                <el-option
                  v-for="item in customerOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="出库说明"
              class="long-content"
              for="outExplain"
            >
              <el-input
                type="textarea"
                :rows="2"
                :disabled="type == 0"
                placeholder="请输入说明"
                v-model="form.outExplain"
                id="outExplain"
                maxlength="120"
              >
              </el-input>
            </el-form-item>
            <el-form-item
              label="鱼品种类"
              prop="fishSpeciesId"
              for="fishSpeciesId"
            >
              <el-select
                v-model="form.fishSpeciesId"
                :disabled="type == 0"
                clearable
                filterable
                placeholder="请选择鱼品种类"
                @change="handleSelectType"
                id="fishSpeciesId"
              >
                <el-option
                  v-for="item in fishSpeciesOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="鱼出库数量"
              prop="fishQuantity"
              for="fishQuantity"
            >
              <el-input-number
                v-model="form.fishQuantity"
                :disabled="type == 0"
                id="fishQuantity"
              ></el-input-number>
            </el-form-item>
            <el-form-item>
              <el-button
                v-if="type == 0 ? false : true"
                type="primary"
                style="margin-left: -50px"
                @click="addSon"
                >添加</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <div>
      <h3>产品信息</h3>
      <el-table
        :data="form.fishSpeciesList"
        header-cell-class-name="table-header"
        style="width: 100%"
        show-overflow-tooltip
      >
        <el-table-column prop="fishSpecies" label="鱼品种类名称" align="center">
        </el-table-column>
        <el-table-column prop="fishSpeciesId" label="鱼品种类id" align="center">
        </el-table-column>
        <el-table-column prop="fishQuantity" label="鱼出库数量" align="center">
        </el-table-column>
      </el-table>
    </div>
    <div>
      <h3>出库信息</h3>

      <EquipmentEx
        ref="EquipmentEx"
        :tableData="form.outList"
        :warehouseId="selectWarehouseId"
        :type="type == 0 ? 0 : 1"
        :treeData="equipmentTreeData"
      />
    </div>
  </div>
</template>

<script>
import EquipmentEx from "../EquipmentEx";
import { getUserCondition } from "@/api/common";
import { addWarehouseEx, updateWarehouseEx } from "@/api/warehouse";
import { getBaseEquipmentType, getCustomer } from "@/api/warehouse";
import { setTreeDisable } from "@/utils/public";
import { querySearchFishType } from "@/api/common";

export default {
  name: "WarehouseExComponent",
  components: {
    EquipmentEx,
  },
  props: {
    // 0:只读 1：修改  2：新增
    type: {
      type: Number,
      default: 0,
    },
    form: {
      type: Object,
      default: function () {
        return {
          id: "",
          outNo: "",
          customerId: "",
          customerName: "",
          operName: "",
          outExplain: "",
          status: "",
          outTime: "",
          operId: "",
          operTime: "",
          fishSpeciesOne: "黑鱼",
          outNumOne: "",
          fishSpeciesTwo: "鲈鱼",
          outNumTwo: "",
          busOutDetailsList: [],
          fishQuantity: 0,
          fishSpeciesId: "",
          fishSpeciesList: [],
          outList: [],
        };
      },
    },
  },
  data() {
    return {
      purchaserLoading: false,
      purchaserOptions: [],
      equipments: [{}, {}, {}, {}],
      equipmentTreeData: [],
      equipmentTreeDataTwo: [],
      selectWarehouseId: "",
      customerOptions: [],
      fishSpeciesOptions: [],
    };
  },
  mounted() {
    getBaseEquipmentType({}).then((res) => {
      this.equipmentTreeData = res.resultData;
      this.equipmentTreeDataTwo = this.equipmentTreeData.slice(0, 2);
    });
    getCustomer({ page: 1, rows: 999 }).then((res) => {
      this.customerOptions = res.resultData;
    });

    querySearchFishType({ remark: 1 }).then((res) => {
      this.fishSpeciesOptions = res.resultData;
    });
    this.selectWarehouseId = this.form.warehouseId + "";
  },
  methods: {
    // 选择客户后给ID赋值
    handleSelectCustomer() {
      const item = this.customerOptions.find(
        (item1) => item1.name === this.form.customerName
      );
      this.form.customerId = item.id;
    },

    handleSelectEquipmentList() {
      getBaseEquipmentType({}).then((res) => {
        this.equipmentTreeData = res.resultData;
        this.form.busOutDetailsList.forEach((res) => {
          if (res.equipmentTypeId) {
            const id = res.equipmentTypeId[res.equipmentTypeId.length - 1];
            setTreeDisable(id, this.equipmentTreeData, true);
          }
        });
        // console.log(this.equipmentTreeData)
      });
    },
    addEquipment() {
      this.validEquipmentData().then((res) => {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            const data = {
              id: "",
              equipmentTypeId: "",
              expirationDate: "",
              outStockNum: "",
              outNum: 0,
              productionDate: "",
              shelfLife: "",
            };
            this.form.busOutDetailsList.push(data);
          } else {
            return false;
          }
        });
      });
    },
    onWarehouseChange(event) {
      this.selectWarehouseId = event + "";
    },
    async validEquipmentData() {
      const equipmentP = [];
      if (this.form.busOutDetailsList != null) {
        for (let i = 0; i < this.form.busOutDetailsList.length; i++) {
          equipmentP.push(this.$refs["EquipmentEx"][i].validData());
        }
      }
      if (equipmentP.length > 0) {
        return Promise.all(equipmentP);
      } else {
        return new Promise((resolve) => resolve());
      }
    },
    saveAndSubmit() {
      this.validEquipmentData().then((res) => {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            // 保存
            const param = { status: 1 };
            Object.assign(param, this.form);
            param.status = 1;
            param.busOutDetailsList.forEach((item) => {
              const lastIndex = item.equipmentTypeId.length - 1;
              item.equipmentTypeId = item.equipmentTypeId[lastIndex];
            });
            addWarehouseEx(param).then((response) => {
              this.$message({
                message: "保存提交成功",
                type: "success",
              });
              this.$emit("onSubmit", {});
            });
          } else {
            return false;
          }
        });
      });
    },
    // onEquipmentDelete(index) {
    //   this.form.busOutDetailsList.splice(index, 1)
    // },

    //添加子集列表
    addSon() {
      if (!this.form.fishSpeciesId) {
        return this.$message({
          message: "请选择鱼品种类",
          type: "error",
        });
      }

      if (!this.form.fishQuantity) {
        return this.$message({
          message: "请输入鱼出库数量",
          type: "error",
        });
      }
      console.log(this.form);
      if (!this.form.fishSpeciesList) {
        this.form.fishSpeciesList = [];
      }
      const index = this.form?.fishSpeciesList.findIndex(
        (item) => item.fishSpeciesId === this.form.fishSpeciesId
      );
      console.log(index, "index");

      const _this = this;
      if (index !== -1) {
        _this
          .$confirm("以下列表有相同的鱼类品种，是否覆盖鱼出库数量", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
          .then(() => {
            _this.form.fishSpeciesList[index].fishQuantity =
              _this.form.fishQuantity;
            _this.$message({
              type: "success",
              message: "更新成功!",
            });

            this.form.fishSpecies = "";
            this.form.fishQuantity = 0;
            this.form.fishSpeciesId = "";
          })
          .catch(() => {
            _this.$message({
              type: "info",
              message: "已取消更新",
            });
          });
      } else {
        // 如果没有相同的，直接push
        this.form.fishSpeciesList.push({
          fishSpecies: this.form.fishSpecies,
          fishSpeciesId: this.form.fishSpeciesId,
          fishQuantity: this.form.fishQuantity,
        });
        this.$message({
          message: "保存成功",
          type: "success",
        });
        this.form.fishSpecies = "";
        this.form.fishQuantity = 0;
        this.form.fishSpeciesId = "";
      }
      // this.form.fishSpeciesList.push({
      //   fishSpecies: this.form.fishSpecies,
      //   fishSpeciesId: this.form.fishSpeciesId,
      //   fishQuantity: this.form.fishQuantity,
      // });
    },

    handleSelectType() {
      const item = this.fishSpeciesOptions.find(
        (item1) => item1.id === this.form.fishSpeciesId
      );
      this.form.fishSpecies = item.name;
    },

    save() {
      this.validEquipmentData().then((res) => {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            this.form.fishSpeciesOne = this.equipmentTreeDataTwo[0].name;
            this.form.fishSpeciesTwo = this.equipmentTreeDataTwo[1].name;
            this.form.outNumOne = this.form.outNum0;
            this.form.outNumTwo = this.form.outNum1;
            // this.form.fishSpeciesOne='黑鱼' //TODO lihuaibei 需要换成实际的产品名称
            // this.form.fishSpeciesTwo='鲈鱼'
            const param = { status: 0 };
            Object.assign(param, this.form);
            param.status = 0;
            // param.busOutDetailsList.forEach(item => {
            //   const lastIndex = item.equipmentTypeId.length - 1
            //   item.equipmentTypeId = item.equipmentTypeId[lastIndex]
            // })

            if (this.type == 2) {
              //新增
              addWarehouseEx(param).then((response) => {
                this.$message({
                  message: "新增成功",
                  type: "success",
                });
                this.$emit("onSave", {});
              });
            } else if (this.type == 1) {
              // 更新
              updateWarehouseEx(param).then((response) => {
                this.$message({
                  message: "更新成功",
                  type: "success",
                });
                this.$emit("onSave", {});
              });
            }
          } else {
            return false;
          }
        });
      });
    },

    /**
     * 模糊查询采购单号
     * @param queryString
     * @param cb
     */
    querySearchOrderNum: function (queryString, cb) {
      // 调用 callback 返回建议列表的数据
      const results = [];
      cb(results);
    },
    /**
     * 选择采购单号
     * @param item
     */
    handleSelectOrderNum(item) {
      // console.log(item)
    },
    /**
     * 模糊查询采购人
     * @param queryString
     * @param cb
     */
    querySearchPurchaser: function (queryString) {
      // 调用 queryString 返回建议列表的数据
      // 使用动态 el-option 来加载
      this.purchaserLoading = true;
      getUserCondition({ userName: queryString, page: 1, rows: 20 }).then(
        (res) => {
          this.purchaserLoading = false;
          this.purchaserOptions = res.resultData;
        }
      );
    },
  },
};
</script>

<style lang="scss" scoped>
.purchase-root {
  max-height: 680px;
  overflow-y: auto;

  ::v-deep .el-form-item__content {
    width: 185px !important;

    .el-date-editor.el-input,
    .el-date-editor.el-input__inner {
      width: 100%;
    }
  }

  ::v-deep .long-content {
    .el-form-item__content {
      width: 480px !important;

      .el-date-editor--datetimerange.el-input,
      .el-date-editor--datetimerange.el-input__inner {
        width: 100%;
      }

      .el-date-editor--daterange.el-input,
      .el-date-editor--daterange.el-input__inner,
      .el-date-editor--timerange.el-input,
      .el-date-editor--timerange.el-input__inner {
        width: 100%;
      }

      .el-cascader--small {
        width: 100%;
      }
    }
  }
}
</style>
